<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form label-width="100px" ref="searchRef" :model="queryParams">
        <el-row>
          <el-col :span="6">
            <el-form-item label="系统名称" prop="name">
              <ns-input v-model="queryParams.name" clearable placeholder="请输入系统名称" />
            </el-form-item>
          </el-col>
          <el-form-item label="所属区域" prop="cityId">
            <el-tree-select
              class="!w-240px"
              v-model="queryParams.cityId"
              :data="areaTree"
              :props="{
                children: 'children',
                label: 'name',
                value: 'id'
              }"
              placeholder="请选择所属区域"
              :default-expanded-keys="expandedKeys"
              value-key="id"
              node-key="id"
            />
          </el-form-item>
          <el-col :span="6">
            <el-form-item label="系统状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择系统状态"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="search" v-hasPermi="['system:info-system:search']"> 搜索</el-button>
            <el-button @click="searchReset" v-hasPermi="['system:info-system:search']"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['system:info-system:add']"
          >新增</el-button
        >
        <el-button
          type="primary"
          plain
          @click="batchCrate"
          v-hasPermi="['system:info-system:batchCrate']"
        >
          批量新增
        </el-button>
        <el-button plain @click="toggleExpandAll"> 展开/折叠</el-button>
        <el-button
          class="ml-4"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:info-system:export']"
        >
          导出
        </el-button>
        <el-button @click="handleImport" v-hasPermi="['system:info-system:import']">
          导入</el-button
        >
      </el-form-item>
      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="list"
        :default-expand-all="isExpandAll"
        row-key="id"
      >
        <el-table-column :show-overflow-tooltip="true" label="系统名称" prop="name" width="250" />
        <!-- <el-table-column label="所属区域" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.provinceName }}/{{ scope.row.cityName }}
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="负责人" prop="headerName" /> -->
        <el-table-column label="排序" prop="orderIndex" />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="创建时间" prop="createTime" />
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openMove(scope.row)"
              v-hasPermi="['system:info-system:transfer']"
              v-if="scope.row.children.length === 0"
            >
              迁移
            </el-button>
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['system:info-system:update']"
            >
              修改
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['system:info-system:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <el-dialog
      v-model="uploadResultDia"
      title="导入结果"
      width="70%"
      v-if="uploadResultDia"
      align-center
    >
      <h2 class="mb-25px">上传成功数量：{{ successQuantity }}</h2>
      <h2 class="my-25px">上传失败数量：{{ failTable.data.length }}</h2>
      <AsyncTable
        v-bind="failTable"
        ref="failTableRef"
        max-height="340px"
        :showSift="false"
        :isPage="false"
      />
      <template #footer>
        <el-button type="primary" @click="uploadResultDia = false">确认</el-button>
      </template>
    </el-dialog>
    <ImportForm ref="importFormRef" @success="getList" />
    <MoveForm ref="moveFormRef" @success="getList" />
    <SystemForm ref="formRef" @success="getList" />
    <BatchCreate :dialogVisible="dialogVisible" @close="close" v-if="dialogVisible" />
  </div>
</template>

<script setup lang="tsx">
import ImportForm from './components/ImportForm.vue'
import MoveForm from './components/MoveForm.vue'
import BatchCreate from './components/BatchCreate.vue'
import * as SystemApi from '@/api/system/infoSystem'
import download from '@/utils/download'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { handleTree } from '@/utils/tree'
import * as AreaApi from '@/api/system/area'
import SystemForm from './SystemForm.vue'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const searchRef = ref()
const isExpandAll = ref(false)
const refreshTable = ref(true)
const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据
const queryParams = ref({
  name: '',
  cityId: '',
  status: ''
})
const uploadResultDia = ref(false)
const dialogVisible = ref(false)

const areaTree = ref() //区域树形结构
/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

const searchReset = () => {
  searchRef.value.resetFields()
  search()
}

const allSelect = ref(false)

const search = () => {
  getList()
}
const successQuantity = ref(0)

const batchCrate = () => {
  dialogVisible.value = true
}
const close = (isAdd) => {
  dialogVisible.value = false
  isAdd && search()
}
const failTable = ref({
  columns: [
    { type: 'index', label: '序号', width: '60px' },
    {
      label: '失败原因',
      render: ({ row }) => {
        return <div>{row}</div>
      },
      'min-width': '340px',
      'show-overflow-tooltip': true
    }
  ],
  data: []
})
/** 查询列表 */
const getList = async (info, isDialog) => {
  if (isDialog) {
    successQuantity.value = info?.createSystemNames?.length
    failTable.value.data = info?.failureSystemNames
    uploadResultDia.value = true
  }
  loading.value = true
  try {
    const data = await SystemApi.getInfoSystemTree(queryParams.value)
    list.value = data
  } finally {
    loading.value = false
  }
}

const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

// 导出
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SystemApi.infoSystemExportExcel({ ...queryParams.value })
    download.excel(data, '信息系统.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SystemApi.deleteSystem(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const moveFormRef = ref()
const openMove = (row) => {
  moveFormRef.value.open(row.id, row.name)
}

/** 获取省市树 */
async function getAreaTree() {
  const res = await AreaApi.getAreaTree2()
  areaTree.value = res
  console.log('res', res)
}

onMounted(() => {
  getAreaTree()
  getList()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
